//
//  PGMeViewController.m
//  youqu
//
//  Created by 彭鹏 on 16/9/3.
//  Copyright © 2016年 pengpeng. All rights reserved.
//

#import "PGMeViewController.h"
#import "PGCollectionViewCell.h"
#import "PGSquareItem.h"

#import "PGHTTPSessionManager.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import "PGWebViewController.h"
#import <SafariServices/SafariServices.h>
#import "PGSettingViewController.h"
@interface PGMeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
/**footCollectionView*/
@property (nonatomic, weak) UICollectionView *footCollectionView;

/**manager*/
@property (nonatomic, weak) PGHTTPSessionManager *manager;

/**squares*/
@property (nonatomic, strong) NSMutableArray *squares;


@end


static NSString *const itemID= @"cell";

NSInteger lineW = 1;
NSInteger cols = 4;

#define itemW (SCREENW-(cols-1)*lineW)/cols

@implementation PGMeViewController

#pragma mark -懒加载manager
- (PGHTTPSessionManager *)manager {
    if (_manager == nil) {
        PGHTTPSessionManager *manager = [PGHTTPSessionManager manager];
        _manager = manager;
    }
    return _manager;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //夜间模式
    UIBarButtonItem *moonBarButtonItem = [UIBarButtonItem barButtonItemWithImageNamed:@"mine-moon-icon" imageSelected:@"mine-moon-icon-click" target:self action:@selector(moonButtonClick:)];
    
    //设置
    UIBarButtonItem *settingBarButtonItem = [UIBarButtonItem barButtonItemWithImageNamed:@"mine-setting-icon" imageHighlighted:@"mine-setting-icon-click" target:self action:@selector(settingButtonClick)];
    
    self.navigationItem.rightBarButtonItems = @[settingBarButtonItem,moonBarButtonItem];
    
    [self setUpTableView];
    
    [self loadData];
    
}

- (void)loadData{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"square";
    parameters[@"c"] = @"topic";
    [self.manager GET:PGBaseUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
//        _squares = [PGSquareItem mj_keyValuesArrayWithObjectArray:responseObject[@"square_list"]];
       
        _squares = [PGSquareItem mj_objectArrayWithKeyValuesArray:responseObject[@"square_list"]];
        
        //总共有多少个模型
        NSUInteger num = _squares.count;
        
        //总共有多少行
        NSUInteger rows = (num - 1) / cols + 1;
        
        //添加额外的空模型
        [self addnilItem:rows];
        
        CGFloat footCollectionViewH = (rows-1)*lineW + rows*itemW;
//        NSLog(@"%zd",_squares.count);
        _footCollectionView.pg_height = footCollectionViewH;
        self.tableView.tableFooterView = _footCollectionView;
        //刷新footCollectioneView
        [_footCollectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)addnilItem:(NSInteger)rows {
    NSInteger num = rows*cols%(_squares.count);
    for (int i=0; i<num; i++) {
        [_squares addObject:[[PGSquareItem alloc] init]];
    }
}

- (void)setUpTableView {
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
    self.tableView.sectionFooterHeight = 10;
    
    //为UICollectionView创建流水布局
    UICollectionViewFlowLayout *flowLayout = ({
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        
        flowLayout.itemSize = CGSizeMake(itemW, itemW);
        flowLayout.minimumLineSpacing = 1;
        flowLayout.minimumInteritemSpacing = 1;
        flowLayout;
    });
    
    
    //创建UICollectionView
    UICollectionView *footCollectionView = ({
        UICollectionView *footCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 300) collectionViewLayout:flowLayout];
        //注册PGCollectionViewCell
        [footCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([PGCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:itemID];
        footCollectionView.backgroundColor = commonBgColor;
        footCollectionView.delegate = self;
        footCollectionView.dataSource = self;
        footCollectionView;
        });
    self.tableView.tableFooterView = footCollectionView;
    _footCollectionView = footCollectionView;
}

#pragma mark -创建设置控制器
- (void)settingButtonClick {
    PGSettingViewController *settingViewController = [[PGSettingViewController alloc] init];
    [self.navigationController pushViewController:settingViewController animated:YES];
}

#pragma mark -开启夜间模式
- (void)moonButtonClick:(UIButton *)btn {
    btn.selected = !btn.selected;
}

//- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
//    return 1;
//}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _squares.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PGCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:itemID forIndexPath:indexPath];
    
    cell.squareItem = self.squares[indexPath.row];
    
    
//        CGFloat footCollectionViewH = CGRectGetMaxY(cell.frame);
//        CGFloat tableViewContentheight = CGRectGetMinY(collectionView.frame) + footCollectionViewH;
//        
//        _footCollectionView.frame = CGRectMake(0, 0, 0, footCollectionViewH);
//        self.tableView.contentSize = CGSizeMake(0, tableViewContentheight);
    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    PGSquareItem *squareItem = _squares[indexPath.row];
    
    if (![squareItem.url hasPrefix:@"http"]) return;
    PGWebViewController *webViewController = [[PGWebViewController alloc] init];
    webViewController.url = squareItem.url;
    [self.navigationController pushViewController:webViewController animated:YES];
//    SFSafariViewController *safariViewController = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:squareItem.url]];
    
//    [self presentViewController:safariViewController animated:YES completion:nil];
//    [self.navigationController pushViewController:safariViewController animated:YES];
    
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 60;
}



@end
